const fs = require('fs');
const path = require('path');
var chokidar = require('./resource/chkoider/index');

//获取脚本执行路径
window.getScriptPath = function () {
    return __dirname
}
window.path = path

//全局根目录
//默认文档保存在用户documents下的IkMarkdown目录下
window.HOME_DIR = window.utools.getPath('documents') + path.sep+"IkMarkdown";
//如果用户手动修改保存目录，那么修改默认读取目录
window.setDocHomeDir = function (path) {
    window.HOME_DIR = path
}

//文件夹监听，当用户从外部修改文件后，编辑器能及时刷新
window.gwtWatcher = function () {
    return chokidar.watch(window.HOME_DIR, {
        ignoreInitial: true,
        ignored: (fs) => fs.match(".swap")
    })
}


//错误码表
window.FILE_IN_USE = "0000"
window.FILE_WRITE_ERROR = "0001"
window.FILE_RENAME_ERROR = "0002"
window.FILE_DEL_ERROR = "0003"
window.FILE_NOT_FOUND = "0004"

//导入文件
window.cpFile = function (src, dist) {
    fs.createReadStream(src).pipe(fs.createWriteStream(dist));
}

//列出documents/IkMarkdown下的markdown文档
window.listDoc = function (path) {

    if (path == null) {
        path = window.HOME_DIR;
        console.log("path---------------------")
        console.log(path)
        if (!fs.existsSync(path)) {
            window.newDir(path, (err) => {
                if (err) {
                    console.log(err)
                }
            })
        }
    }
    let data = fileDisplay(path)
    return data
}

//读取markdown文件
window.readFile = function (path, callBack) {
    fs.readFile(path, 'utf8', (err, data) => {
        callBack(err, data);
    })
}

//新建文件夹
window.newDir = function (path, callBack) {
    console.log("新建文件夹" + path)
    console.log(path)
    if (fs.existsSync(path)) {
        var stats = fs.lstatSync(path)
        if (stats.isFile()) {
            callBack("该路径已存在且为文件，请重新选择")
        } else {
            callBack(null)
        }

    } else {
        fs.mkdir(path, (err) => {
            callBack(err)
        })
    }

}

//重命名
window.rename = function (path, newPath, callBack) {
    fs.rename(path, newPath, (err) => {
        callBack(err, window.FILE_RENAME_ERROR)
    })
}

//新建文件
window.newFile = function (path, callBack) {
    try {
        if (!fs.existsSync(path)) {
            //写入文件（会覆盖之前的内容）（文件不存在就创建）  utf8参数可以省略
            fs.writeFile(path, '', 'utf8', function (error) {
                callBack(error)
            })
        }
    } catch (err) {
        callBack("文件已经存在！" + err)
    }
}

//修改保存文件
window.reWrite = function (path, str, callBack) {
    if (!fs.existsSync(path)) {
        callBack("文件不存在", window.FILE_NOT_FOUND)
        return
    }
    let tmpFile = path + ".swap"
    if (fs.existsSync(tmpFile)) {
        callBack("文件正在占用中！", window.FILE_IN_USE)
    } else {
        fs.writeFile(tmpFile, str, 'utf8', function (error) {
            if (error) {
                callBack(error, window.FILE_WRITE_ERROR)
            } else {
                window.delFile(path, (err) => {
                    if (err) {
                        callBack(err, window.FILE_DEL_ERROR)
                    } else {
                        window.rename(tmpFile, path, callBack)
                    }
                })
            }
        })
    }
}

//删除文件
window.delFile = function (path, callBack) {
    //根据文件路径获取文件信息，返回一个fs.Stats对象
    var stats = fs.lstatSync(path)
    if (stats.isFile()) {
        fs.unlink(path, (err) => {
            callBack(err)
        });
    } else {
        fs.rmdir(path, {
            recursive: true,//递归删除
        }, (error) => {
            if (error) {
                console.log(error);
                callBack(error);
            } else {
                callBack()
            }
        });
    }
}

/**
 * 文件遍历方法
 * @param filePath 需要遍历的文件路径
 */
function fileDisplay(filePath) {
    var foldersList = [];
    var filesList = [];
    var id = 0;
    //根据文件路径读取文件，返回文件列表
    var files = fs.readdirSync(filePath)

    //遍历读取到的文件列表
    files.forEach(function (filename) {
        id = id + 1;
        //获取当前文件的绝对路径
        var filedir = path.join(filePath, filename)
        //根据文件路径获取文件信息，返回一个fs.Stats对象
        var stats = fs.lstatSync(filedir)
        var isFile = stats.isFile()//是文件
        var isDir = stats.isDirectory()//是文件夹
        if (isFile) {
            filesList.push({name: filename, leaf: true, path: filedir, id: process.uptime(), isCreated: true})
        }
        if (isDir) {
            foldersList.push({name: filename, leaf: false, path: filedir, id: process.uptime(), isCreated: true})
        }

    })

    return foldersList.concat(filesList)
}
